package com.kakahair.plat.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.kakahair.common.controller.BaseController;
import com.kakahair.common.util.AjaxResponse;
import com.kakahair.plat.entity.Evaluation;
import com.kakahair.plat.service.EvaluationService;

import net.sf.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Tiddar
 * @since 2018-04-07
 */
@Controller
@RequestMapping("/evaluation")
public class EvaluationController extends BaseController {

	@Autowired
	EvaluationService evaluationService;

	private String uploadPath;

	public String getUploadPath() {
		return uploadPath;
	}

	public void setUploadPath(String uploadPath) {
		this.uploadPath = uploadPath;
	}

	/**
	 * 
	 * @author TiddAr
	 * @Title: insert
	 * @Description: 添加评论
	 * @param @param
	 *            evaluation
	 * @param @param
	 *            files
	 * @param @return
	 *            参数
	 * @return AjaxResponse 返回类型
	 * @throws UnsupportedEncodingException
	 * @date 2018年4月9日
	 * 
	 */
	@ResponseBody
	@RequestMapping(value = "/submit", method = RequestMethod.POST)
	public AjaxResponse insert(@RequestParam(value = "imgs", required = false) CommonsMultipartFile[] files,
			Integer star, String content, Integer technicianId, String orderId) throws UnsupportedEncodingException {
		System.out.println(content.getBytes("UTF-8"));
		AjaxResponse ajaxResponse = AjaxResponse.instance();
		try {

			// 如果目录不存在，创建一个目录
			if (!new File(uploadPath).exists()) {
				File dir = new File(uploadPath);
				dir.mkdirs();
			}
			System.out.println("上传评论图片start,共上传:" + files.length + "个图片");
			logger.debug("上传评论图片start,共上传:" + files.length + "个图片");
			Map<String, Object> data = new HashMap<String, Object>();
			List<String> pics = new ArrayList<String>();
			for (MultipartFile file : files) {
				String fileName = file.getOriginalFilename();
				System.out.println("原始文件名:" + fileName);
				String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toLowerCase();
				data.put("fileType", fileType);
				if ("jpg".equals(fileType) || "png".equals(fileType)) {
					// 新文件名
					fileName = UUID.randomUUID() + "." + fileType;
					String path = uploadPath + fileName;
					File localFile = new File(path);
					file.transferTo(localFile);
					ajaxResponse.setSuccess(true);
					ajaxResponse.setMessage("上传成功");
					logger.debug("上传评论图片成功!");
					pics.add(fileName);
				} else {
					ajaxResponse.setSuccess(false);
					ajaxResponse.setMessage("文件格式非法");
				}
			}
			data.put("文件名:", pics);
			ajaxResponse.setData(data);
			System.out.println("上传评论图片end");
			evaluationService.evaluate(new Evaluation().setTime(new Date()).setAdd(content).setKey(star)
					.setOrderId(orderId).setTechnicianId(technicianId).setPics(pics.toArray(new String[pics.size()])));
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			logger.error("上传图片失败" + e.getMessage());
			ajaxResponse.setSuccess(false);
			ajaxResponse.setMessage("服务器故障");
		}
		return ajaxResponse;
	}

	@ResponseBody
	@PostMapping(value = "/submitNoPic")
	public AjaxResponse submitNoPic(@RequestBody JSONObject data) {
		AjaxResponse ajaxResponse = AjaxResponse.instance();
		try {
			Evaluation evaluation = new Evaluation().setTime(new Date()).setAdd(data.getString("content"))
					.setOrderId(data.getString("orderId")).setKey(data.optInt("star", 5))
					.setTechnicianId((data.getInt("technicianId")));
			evaluationService.evaluate(evaluation);
			ajaxResponse.setSuccess(true);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			ajaxResponse.setSuccess(false);
			ajaxResponse.setMessage("评论失败" + e.getLocalizedMessage());
		}
		return ajaxResponse;
	}

	@ResponseBody
	@RequestMapping(value = "/listshop/{shopId}", method = RequestMethod.GET)
	public AjaxResponse shopList(@PathVariable Integer shopId) {
		AjaxResponse ajaxResponse = AjaxResponse.instance();
		try {
			List<Evaluation> evaluations = evaluationService.listByShopId(shopId);
			ajaxResponse.setData(evaluations);
			ajaxResponse.setSuccess(true);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			ajaxResponse.setSuccess(false);
			ajaxResponse.setMessage("查询评论失败" + e.getLocalizedMessage());
		}
		return ajaxResponse;

	}

	@ResponseBody
	@GetMapping("/listshopall/{shopId}/{pageIndex}")
	public AjaxResponse shopListAll(@PathVariable Integer shopId, @PathVariable Integer pageIndex) {
		AjaxResponse ajaxResponse = AjaxResponse.instance();
		try {
			List<Evaluation> evaluations = evaluationService.listAllByShopId(shopId, pageIndex);
			ajaxResponse.setData(evaluations);
			ajaxResponse.setSuccess(true);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			ajaxResponse.setSuccess(false);
			ajaxResponse.setMessage("查询评论失败" + e.getLocalizedMessage());
		}
		return ajaxResponse;

	}

	@ResponseBody
	@GetMapping("/listtech/{techId}/{pageIndex}")
	public AjaxResponse shopListTech(@PathVariable Integer techId, @PathVariable Integer pageIndex) {
		AjaxResponse ajaxResponse = AjaxResponse.instance();
		try {
			List<Evaluation> evaluations = evaluationService.listByTechId(techId, pageIndex);
			ajaxResponse.setData(evaluations);
			ajaxResponse.setSuccess(true);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			ajaxResponse.setSuccess(false);
			ajaxResponse.setMessage("查询评论失败" + e.getLocalizedMessage());
		}
		return ajaxResponse;

	}

}
